package cn.texous.web.parsing.book.service.impl.mysql;

import cn.texous.util.commons.exception.BusinessException;
import cn.texous.util.commons.util.StringUtils;
import cn.texous.web.parsing.book.common.constants.AnaResultCode;
import cn.texous.web.parsing.book.common.constants.NormalStatusEnum;
import cn.texous.web.parsing.book.config.mysql.AbstractService;
import cn.texous.web.parsing.book.dao.mysql.AnaUserBookMapper;
import cn.texous.web.parsing.book.model.entity.mysql.AnaBookChapter;
import cn.texous.web.parsing.book.model.entity.mysql.AnaUserBook;
import cn.texous.web.parsing.book.model.param.AnaBookshelfReadPointParam;
import cn.texous.web.parsing.book.service.api.mysql.AnaBookChapterService;
import cn.texous.web.parsing.book.service.api.mysql.AnaUserBookService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * insert description here.
 *
 * @author Showa.L
 * @since 2020-03-11 14:20:37
 */
@Service
public class AnaUserBookServiceImpl
        extends AbstractService<AnaUserBook> implements AnaUserBookService {

    @Resource
    private AnaUserBookMapper anaUserBookMapper;
    @Resource
    private AnaBookChapterService anaBookChapterService;

    @Override
    public Integer insertOrUpdate(AnaUserBook userBook) {
        return anaUserBookMapper.insertOrUpdate(userBook);
    }

    @Override
    public Integer insertOrUpdate(String bookCode, String chapterCode, Integer userId) {
        if (userId != null) {
            // 存储用户阅读记录
            AnaUserBook userBook = new AnaUserBook();
            userBook.setAnaUserId(userId);
            userBook.setAnaBookCode(bookCode);
            userBook.setAnaBookChapterCode(chapterCode);
            userBook.setStatus(NormalStatusEnum.AVAILABLE.getCode());
            return anaUserBookMapper.insertOrUpdate(userBook);
        }
        return null;
    }

    @Override
    public String getReadPoint(AnaBookshelfReadPointParam param, Integer userId) {
        if (userId != null) {
            AnaUserBook book = anaUserBookMapper.getReadHistory(userId, param.getAnaBookCode());
            if (book != null && !StringUtils.isTrimEmpty(book.getAnaBookChapterCode()))
                return book.getAnaBookChapterCode();
        }

        AnaBookChapter chapter = anaBookChapterService.getFirstChapterByCache(param.getAnaBookCode());
        if (chapter == null)
            throw new BusinessException(AnaResultCode.FS_BOOK_CHAPTER_NOT_EXISTS_ERROR);

        return chapter.getCode();
    }
}
